package main.剑指OfferⅠ;

public class Day12 {
    public static void main(String[] args) {
        System.out.println("剑指Offer25.合并两个排序的链表");
        System.out.println("剑指Offer52.两个链表的第一个公共节点");
    }
}

class Offer25{
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode vir=new ListNode(0),last=vir;
        while (l1!=null&&l2!=null){
            ListNode cur=null;
            if (l1.val< l2.val){
                cur=new ListNode(l1.val);
                l1=l1.next;
            }else {
                cur=new ListNode(l2.val);
                l2=l2.next;
            }
            last.next=cur;
            last=cur;
        }
        while (l1!=null){
            ListNode cur=new ListNode(l1.val);
            last.next=cur;
            last=cur;
            l1=l1.next;
        }
        while (l2!=null){
            ListNode cur=new ListNode(l2.val);
            last.next=cur;
            last=cur;
            l2=l2.next;
        }
        return vir.next;
    }
}

class Offer52{
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode tempA=headA,tempB=headB;
        while (tempA!=null&&tempB!=null){
            tempA=tempA.next;
            tempB=tempB.next;
        }
        if (tempA==null){//换路，寻找路差
            tempA=headB;
            while (tempB!=null){
                tempB=tempB.next;
                tempA=tempA.next;
            }
            tempB=headA;
        }else {
            tempB=headA;
            while (tempA!=null){
                tempA=tempA.next;
                tempB=tempB.next;
            }
            tempA=headB;
        }
        while (tempA!= tempB){
            tempA=tempA.next;
            tempB=tempB.next;
        }
        return tempA;
    }
}